package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.ParmasException;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 操作菜品分类的业务逻辑代码
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    /**
     * 分页查询
     * @param pages
     * @param pageSize
     * @return
     */
    @Override
    public Page<Category> findPage(Integer pages, Integer pageSize) {
        //创建条件对象
        QueryWrapper<Category> wrapper =new QueryWrapper();
        //以什么排序
        wrapper.orderByAsc("sort").orderByDesc("update_time");
        Page<Category> pageInfo = this.page(new Page<>(pages, pageSize),wrapper);
        return pageInfo;
    }

    /**
     * 根据id删除信息
     * @param id
     */
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public void delete(Long id) {
        //查询当前分类是否关联了菜品,如果关联了菜品就抛出一个异常
        //创建条件对象
        LambdaQueryWrapper<Dish> wrapper =new LambdaQueryWrapper();
        wrapper.eq(Dish::getCategoryId,id);
        //调用菜品的方法,查看里面的数据
        int count = dishService.count(wrapper);
        //判断
        if (count>0){
            //获取异常
            throw  new ParmasException("已经关联菜品,无法处理");
        }

        LambdaQueryWrapper<Setmeal> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId,id);
        //调用套餐里面的的方法,查询数据
        int count1 = setmealService.count(queryWrapper);
        if (count1>0){
            //直接获取异常,
            throw  new ParmasException("已经关联套餐,无法处理");
        }
        //正常删除
        this.removeById(id);
    }
}
